import java.util.Collections;

public class TextWriter {

    private StringBuilder sb = new StringBuilder();
    private int indent = 0;
    private int indentSize = 4;
    private boolean lineStart = true;
    static public final String lineBreak = "\n";

    public void writeString(String str) {
        if (lineStart)  {
            sb.append(String.join("", Collections.nCopies(indent*indentSize, " ")));
            lineStart = false;
        }

        if (str.length() > 0 && str.length() - str.lastIndexOf(lineBreak) == lineBreak.length()){
            lineStart = true;
        }
        sb.append(str);
    }

    public void writeLine() {
        if (!lineStart){
            sb.append('\n');
            lineStart = true;
        }
    }

    public void writeEmptyLine() {
        writeString(lineBreak);
    }

    public void increaseIndent() {
        indent ++;
    }

    public void decreaseIndent() {
        indent --;
    }

    public void removeTrailing(String text) {
        if (sb.lastIndexOf(text) == sb.length()-text.length()) {
            sb.delete(sb.length()-text.length(), sb.length());
        }
    }

    @Override
    public String toString() {
        return sb.toString();
    }
}
